package com.example.demo.common.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.common.entity.Defect;
import com.example.demo.common.entity.Sample;
import com.example.demo.common.mapper.DefectMapper;
import com.example.demo.common.service.DefectService;
import com.example.demo.common.utils.IpUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
@CrossOrigin
@RestController
@RequestMapping("/defect")
public class DefectController {
    @Resource
    DefectService defectService;
    @Resource
    DefectMapper defectMapper;
    @Resource
    IpUtil ipUtil;
    @PostMapping
    public Result<?> save(@RequestBody Defect defect){
        defectService.saveDefect(replceIP(defect));
        return Result.success();
    }
    @PutMapping
    public Result<?> update(@RequestBody Defect defect){
        defectService.updateDefect(replceIP(defect));
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id){
        defectService.deleteById(id);
        return Result.success();
    }
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Defect> wrapper = Wrappers.<Defect>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(Defect::getRef, search);
        }
        Page<Defect> defectPage = defectMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(defectPage);
    }
    public Defect replceIP(Defect defect){
        if (defect.getZhupiImage() !=null&& !defect.getZhupiImage().equals("")){
            defect.setZhupiImage(defect.getZhupiImage().replace("http://"+ipUtil.getIp()+"/1/",""));
        }
        if (defect.getDetectImage() !=null&& !defect.getDetectImage().equals("")){
            defect.setDetectImage(defect.getDetectImage().replace("http://"+ipUtil.getIp()+"/1/",""));
        }
        return defect;
    }
}
